<template>
  <div>
    <a-page-header
      style="border: 1px solid rgb(235, 237, 240); margin-bottom:14px"
      title="创建SKU"
    >
    </a-page-header>

    <div>
      <a-form :form="form" layout="vertical" @submit="handleSubmit">
        <a-row :gutter="8">
          <a-col :sm="16" :xs="24">
            <a-card title="基本信息">
              <a-form-item
                label="SKU编码"
                help="SKU编码支持数字，字母，-，_，#，*，/，&，+，?，.，(，)，@；长度最大支持24位"
              >
                <a-input
                  v-decorator="[
                    'code',
                    {
                      rules: [{ required: true, message: '必填!', max: 24 }]
                    }
                  ]"
                ></a-input>
              </a-form-item>
              <a-form-item
                label="SKU名称"
                help="货品详细名称，建议长度控制在50位内"
              >
                <a-input
                  v-decorator="[
                    'subject',
                    {
                      rules: [{ required: true, message: '必填!', max: 50 }]
                    }
                  ]"
                ></a-input>
              </a-form-item>
              <a-form-item label="海外仓库">
                <a-select
                  show-search
                  placeholder="选择仓库"
                  v-decorator="[
                    'warehouse_id',
                    {
                      rules: [{ required: true, message: '必选!' }]
                    }
                  ]"
                >
                  <a-select-option
                    v-for="warehouse in warehouses"
                    :key="warehouse.id"
                    :value="warehouse.id"
                  >
                    {{ warehouse.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item
                label="产品编码"
                help="产品编码支持数字、字母、小数点、中横杠或下横杠。例如UPC、EAN、JAN、ISBN"
              >
                <a-input v-decorator="['product_code']"></a-input>
              </a-form-item>

              <a-form-item
                label="销售单位"
                help="化妆品类货品,单位请填写ml/g/片"
              >
                <a-select
                  show-search
                  placeholder="选择销售单位"
                  v-decorator="[
                    'sell_unit',
                    {
                      rules: [{ required: true, message: '必选!' }]
                    }
                  ]"
                >
                  <a-select-option
                    v-for="unit in units"
                    :key="unit.id"
                    :value="unit.id"
                  >
                    {{ unit.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="包装形态">
                <a-radio-group
                  v-decorator="[
                    'wrapping',
                    {
                      rules: [{ required: true, message: '必填!' }]
                    }
                  ]"
                  :options="[
                    { label: '硬包装', value: '1' },
                    { label: '软包装', value: '2' }
                  ]"
                />
              </a-form-item>
              <a-form-item label="包装材质">
                <a-select
                  placeholder="选择材质"
                  v-decorator="[
                    'package_material',
                    {
                      rules: [{ required: true, message: '必选!' }]
                    }
                  ]"
                >
                  <a-select-option
                    v-for="material in materials"
                    :key="material.id"
                    :value="material.id"
                  >
                    {{ material.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="重量">
                <a-input
                  v-decorator="[
                    'weight',
                    {
                      rules: [{ required: true, message: '必填!' }]
                    }
                  ]"
                  suffix="KG"
                ></a-input>
              </a-form-item>
              <a-form-item label="长*宽*高">
                <a-row>
                  <a-col span="6">
                    <a-input
                      v-decorator="[
                        'length',
                        {
                          rules: [{ required: true, message: '必填!' }]
                        }
                      ]"
                    ></a-input>
                  </a-col>
                  <a-col span="1">
                    <div style="text-align:center">*</div>
                  </a-col>
                  <a-col span="6">
                    <a-input
                      v-decorator="[
                        'width',
                        {
                          rules: [{ required: true, message: '必填!' }]
                        }
                      ]"
                    ></a-input>
                  </a-col>
                  <a-col span="1"><div style="text-align:center">*</div></a-col>
                  <a-col span="6">
                    <a-input
                      v-decorator="[
                        'height',
                        {
                          rules: [{ required: true, message: '必填!' }]
                        }
                      ]"
                    ></a-input>
                  </a-col>
                  <a-col span="2"
                    ><div style="text-align:center">CM</div></a-col
                  >
                </a-row>
              </a-form-item>
              <a-form-item label="特性">
                <a-checkbox-group
                  v-decorator="['characteristic']"
                  :options="characteristicOptions"
                />
              </a-form-item>
              <a-form-item label="包装类型">
                <a-checkbox
                  v-decorator="[
                    'logistics_package',
                    { valuePropName: 'checked' }
                  ]"
                >
                  自带物流包装
                </a-checkbox>
              </a-form-item>
              <a-form-item label="电池标识">
                <a-radio-group
                  v-decorator="['is_battery', { initialValue: '1' }]"
                  :options="[
                    { label: '不带电池', value: '1' },
                    { label: '带有电池', value: '2' }
                  ]"
                  @change="handlerButtery"
                />
              </a-form-item>
              <a-form-item v-if="is_battery" label="电池配置">
                <a-select
                  placeholder="请选择"
                  v-decorator="[
                    'battery_config',
                    {
                      rules: [{ required: true, message: '必选!' }]
                    }
                  ]"
                >
                  <a-select-option
                    v-for="config in battery_configs"
                    :key="config.id"
                    :value="config.id"
                  >
                    {{ config.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item v-if="is_battery" label="电池类型">
                <a-select
                  placeholder="请选择"
                  v-decorator="[
                    'battery_type',
                    {
                      rules: [{ required: true, message: '必选!' }]
                    }
                  ]"
                >
                  <a-select-option
                    v-for="btype in battery_types"
                    :key="btype.id"
                    :value="btype.id"
                  >
                    {{ btype.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item
                v-if="is_battery"
                label="电池功率"
                help="Wh 功率=电压*电流"
              >
                <a-input
                  v-decorator="[
                    'battery_power',
                    {
                      rules: [{ required: true, message: '必填!' }]
                    }
                  ]"
                ></a-input>
              </a-form-item>
              <a-form-item v-if="is_battery" label="电池数量">
                <a-input
                  v-decorator="[
                    'battery_number',
                    {
                      rules: [{ required: true, message: '必填!' }]
                    }
                  ]"
                ></a-input>
              </a-form-item>
              <a-form-item v-if="is_battery" label="MSDS">
                <a-upload
                  name="file"
                  :action="uploadUrl"
                  @change="handleMsdsChange"
                >
                  <a-button> <a-icon type="upload" /> 上传 </a-button>
                </a-upload>
              </a-form-item>
              <a-form-item label="SN码管理">
                <a-radio-group
                  v-decorator="['is_sn', { initialValue: '1' }]"
                  :options="[
                    { label: '否', value: '1' },
                    { label: '是', value: '2' }
                  ]"
                  @change="handleSn"
                />
              </a-form-item>
              <a-form-item v-if="is_sn" label="SN码规则">
                <a-select
                  show-search
                  placeholder="选择规则"
                  v-decorator="[
                    'sn_rule',
                    {
                      rules: [{ required: true, message: '必选!' }]
                    }
                  ]"
                >
                  <a-select-option
                    v-for="rule in rules"
                    :key="rule.id"
                    :value="rule.id"
                  >
                    {{ rule.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item
                label="销售采购链接"
                help="用分号隔开多个链接 请保证销售链接长期有效，若无效，会导致清关失败，影响清关时效"
              >
                <a-input
                  v-decorator="[
                    'sales_link',
                    {
                      rules: [{ required: true, message: '必填!' }]
                    }
                  ]"
                ></a-input>
              </a-form-item>
              <a-form-item label="规格属性">
                <a-textarea
                  :auto-size="{ minRows: 3, maxRows: 5 }"
                  v-decorator="['specification']"
                ></a-textarea>
              </a-form-item>
              <a-form-item label="备注">
                <a-textarea
                  :auto-size="{ minRows: 3, maxRows: 5 }"
                  v-decorator="['remark']"
                ></a-textarea>
              </a-form-item>
            </a-card>
          </a-col>
          <a-col :sm="8" :xs="24">
            <a-card title="与电商平台SKU关联" style="margin-bottom:15px;">
              <a-form-item style="margin-bottom:0">
                <a-input-group compact>
                  <a-input
                    v-decorator="['alibaba_sku']"
                    addon-before="阿里巴巴"
                    placeholder="请填写阿里巴巴SKU"
                  />
                </a-input-group>
              </a-form-item>
            </a-card>
            <a-card title="图片信息">
              <a-alert class="pic_notice" type="warning">
                <ul slot="description">
                  <li>图片大小不能超过10MB，格式为jpg、jpeg、png;</li>
                  <li>
                    建议使用500*500像素的图片，至少上传两张销售包装图片和两张产品图片，有文字和图案的那面必须上传;
                  </li>
                  <li>最大支持上传6张图片，要求能够全面展现SKU情况。</li>
                </ul>
              </a-alert>
              <a-upload
                :action="uploadUrl"
                list-type="picture-card"
                :file-list="fileList"
                @preview="handlePreview"
                @change="handleChange"
              >
                <div v-if="fileList.length < 6">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    上传
                  </div>
                </div>
              </a-upload>
              <a-modal
                :visible="previewVisible"
                :footer="null"
                @cancel="handleCancel"
              >
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-card>
          </a-col>
        </a-row>
        <div class=""></div>
        <a-card style="margin-top:15px; text-align:right">
          <a-button type="primary" html-type="submit" :loading="confirmLoading">
            提交
          </a-button>
        </a-card>
      </a-form>
    </div>
  </div>
</template>

<script>
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default {
  data() {
    return {
      form: this.$form.createForm(this),
      is_battery: false,
      warehouses: [],
      units: [],
      materials: [],
      characteristicOptions: [
        { label: "带插座", value: "1" },
        { label: "带液体", value: "2" },
        { label: "带光盘", value: "3" },
        { label: "易碎品", value: "4" },
        { label: "带粉末", value: "5" },
        { label: "膏状", value: "6" },
        { label: "贵重货品", value: "7" },
        { label: "恒温保存", value: "8" },
        { label: "危险货品", value: "9" }
      ],
      battery_configs: [],
      battery_types: [],
      is_sn: false,
      rules: [],
      confirmLoading: false,
      uploadUrl: process.env.VUE_APP_BACKGROUND_API + "/api/upload",
      previewVisible: false,
      previewImage: "",
      fileList: [],
      msdsFileList: []
    };
  },
  created() {
    this.fetchIndexData();
  },
  methods: {
    fetchIndexData() {
      this.fetchHouse();
      this.fetchSellUnit();
      this.fetchPackageMaterial();
      this.fetchBatteryConfig();
      this.fetchBatteryType();
      this.fetchSkuRule();
    },
    fetchHouse() {
      this.$axios
        .get(process.env.VUE_APP_BACKGROUND_API + "/api/warehouses")
        .then(response => {
          this.warehouses = response.data;
        });
    },
    fetchSellUnit() {
      this.$axios
        .get(process.env.VUE_APP_BACKGROUND_API + "/api/sell_unit")
        .then(response => {
          this.units = response.data;
        });
    },
    fetchPackageMaterial() {
      this.$axios
        .get(process.env.VUE_APP_BACKGROUND_API + "/api/package_material")
        .then(response => {
          this.materials = response.data;
        });
    },
    fetchBatteryConfig() {
      this.$axios
        .get(process.env.VUE_APP_BACKGROUND_API + "/api/battery_config")
        .then(response => {
          this.battery_configs = response.data;
        });
    },
    fetchBatteryType() {
      this.$axios
        .get(process.env.VUE_APP_BACKGROUND_API + "/api/battery_type")
        .then(response => {
          this.battery_types = response.data;
        });
    },
    fetchSkuRule() {
      this.$axios
        .get(process.env.VUE_APP_BACKGROUND_API + "/api/sku_rule")
        .then(response => {
          this.rules = response.data;
        });
    },
    handlerButtery(e) {
      this.is_battery = e.target.value === "2";
    },
    handleSn(e) {
      this.is_sn = e.target.value === "2";
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange({ fileList }) {
      this.fileList = fileList;
    },
    handleMsdsChange(info) {
      if (info.file.status !== "uploading") {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} 文件上传成功.`);
        this.msdsFileList = info.fileList;
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} 文件上传失败.`);
      }
    },
    handleSubmit(e) {
      e.preventDefault();
      this.confirmLoading = true;
      let thumbs = [];
      let battery_msds = [];

      this.form.validateFields((err, values) => {
        this.fileList.forEach(e => {
          thumbs.push(e.response);
        });
        this.msdsFileList.forEach(e => {
          battery_msds.push(e.response);
        });
        if (!err) {
          values["thumbs"] = thumbs;
          values["battery_msds"] = battery_msds;
          this.$axios
            .post(process.env.VUE_APP_BACKGROUND_API + "/api/sku", values)
            .then(response => {
              this.$message.success(response.data.msg);
              this.$router.push("/dashboard/skus");
              this.form.resetFields();
              this.fileList = [];
            })
            .catch(error => {
              this.$message.error(error.message);
              this.confirmLoading = false;
            });
        }

        this.confirmLoading = false;
      });
    }
  }
};
</script>

<style lang="scss">
.ant-form-vertical .ant-form-item {
  margin-bottom: 15px;
}
.pic_notice {
  &.ant-alert {
    margin-bottom: 15px;
  }
  ul,
  li {
    list-style: none;
  }
  ul {
    padding: 0;
    margin: 0;
  }
}
</style>
